function f = marginal_effect(theta2,mean_coef,rand_coef,rd,v,x2,var,delta,ind_market,sj,QI)

ns=length(rd);
numobs=length(delta);
expdelta=exp(delta);
nmrkt=max(ind_market);

%recover price

alpha=mean_coef;
sigmap=rand_coef;
ddelt=alpha+sigmap*repmat(rd,numobs,1); 
expmu1=expmu(theta2,v,x2,var);  

s1=ind_shares(expdelta,expmu1,QI,ind_market); 

A2=cell(1,1,nmrkt); 
%A2=zeros(numobs,numobs); 

for q=1:nmrkt 
    tempp=(ind_market==q);
    s11=s1(tempp,:);
    s11star=s11.*ddelt(tempp,:);
    %A2{1,1,q}=(1./sj(tempp)').*diag(mean(s11star.*(1-s11),2))-(1-eye(size(s11,1),size(s11,1))).*(s11star*s11'./ns); 
    A2{1,1,q}=diag(mean(s11star.*(1-s11),2))-(1-eye(size(s11,1),size(s11,1))).*(s11star*s11'./ns); 
end
f=A2;